package cn.tonyandmoney.voicenotes.notes.model

import cn.tonyandmoney.voicenotes.greendao.gen.NoteRecordDao
import cn.tonyandmoney.voicenotes.greendao.gen.TNoteDao
import cn.tonyandmoney.voicenotes.greendao.gen.TRecordDao
import cn.tonyandmoney.voicenotes.greendao.utils.GreenDaoHelper
import cn.tonyandmoney.voicenotes.notes.entity.NoteRecord
import cn.tonyandmoney.voicenotes.notes.entity.TRecord
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import org.jetbrains.anko.AnkoLogger
import org.jetbrains.anko.info
import java.io.File

/**
 * 文件管理
 */
class FileModel : AnkoLogger {
    private val mRecordDao = GreenDaoHelper.session().tRecordDao

    fun list(callback: (List<TRecord>, String?) -> Unit) {
        Observable.create<List<TRecord>> {
            it.onNext(mRecordDao.loadAll())
            it.onComplete()
        }.subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({ callback.invoke(it, null) },
                        { callback.invoke(emptyList(), it.message ?: "加载失败。") })
    }

    /**
     * 删除之后清除缓存
     */
    fun delete(record: TRecord) {
        mRecordDao.delete(record)
        val file = File(record.path)
        if (file.exists()) file.delete()
        val sql = "delete from ${NoteRecordDao.TABLENAME} where ${NoteRecordDao.Properties.RecordId.columnName}=${record.id}"
        GreenDaoHelper.session().database.execSQL(sql)
        info("delete $record")
        GreenDaoHelper.session().clear()
    }

    /**
     * 文件所属的笔记名称，备注，文件名，
     */
    fun searchBy(keywords: String): List<TRecord> {
        if (keywords.isBlank())
            return mRecordDao.loadAll()
        val notes = GreenDaoHelper.session().tNoteDao
                .queryBuilder()
                .whereOr(TNoteDao.Properties.Name.like("%$keywords%"),
                        TNoteDao.Properties.Memo.like("%$keywords%"),
                        TNoteDao.Properties.Content.like("%$keywords%"))
                .list()
        if (notes.isEmpty()) return emptyList()

        val fileIds = GreenDaoHelper.session().noteRecordDao
                .queryBuilder()
                .where(NoteRecordDao.Properties.NoteId.`in`(notes.map { it.id }))
                .list()
                .map { it.recordId }

        if (fileIds.isEmpty()) return emptyList()
        return mRecordDao.queryBuilder()
                .where(TRecordDao.Properties.Id.`in`(fileIds))
                .list()

    }


}